import mysql2 from 'mysql2/promise';

let pool = null;

export const createPool = function () {
  pool = mysql2.createPool({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASES,
    dateStrings: true
  });
};

export const executeSql = async function (sql, params = []) {
  let conn = null;
  try {
    conn = await pool.getConnection();
    let [data] = await conn.execute(sql, params);
    return data;
  } catch (error) {
    throw error;
  } finally {
    if (conn) {
      conn.release();
      conn = null;
    }
  }
};